package model.textChat;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;

import com.ibm.icu.util.Calendar;

import model.infocenter.ClientUserInformations;
import model.textChat.Interface.MessageSending;

public class MessageSender implements MessageSending
{
	private BufferedWriter mSender = null; 

	@Override
	public synchronized boolean send(String content)
	{
		System.out.println( "******** New Message Content: " + content );
		if ( mSender != null )
		{
			Message message = formatMessage( content );
			try
			{
				mSender.write( message.getSendTime() + "\n" );
				mSender.flush();
				mSender.write( message.getSenderName() + "\n" );
				mSender.flush();
				char endMark = 3;  // The mark of end of content
				mSender.write( message.getContent() + "\n" + endMark + "\n" );
				mSender.flush();
				
				return true;
			}
			catch (Exception e)
			{
				try
				{
					mSender.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
			}
		}
		
		return false;
	}
	
	private Message formatMessage(String content)
	{
		ClientUserInformations clientUser = ClientUserInformations.getInstance();
		String senderName = clientUser.getUserName();
		Calendar curTime = Calendar.getInstance();
		SimpleDateFormat dFormat = new SimpleDateFormat( "yyyy/MM/dd-HH:mm:ss" );
		String curTimeString = dFormat.format( curTime.getTime() );
		
		Message message = new Message( senderName, curTimeString, content );
		
		return message;
	}
	
	@Override
	public synchronized void update( Socket socket )
	{
		try
		{
			ClientUserInformations clientUser = ClientUserInformations.getInstance();
			int roomId = clientUser.getCurRoomId();

		

			mSender = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
			mSender.write( "" + roomId + "\n" );
			mSender.flush();

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
